<?php


namespace wechat\lib\core;


use wechat\lib\Http;

class Menu extends Base
{
    static private $instance;

    private function __construct($appid,$appsecret)
    {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    static public function getInstance($appid,$appsecret)
    {
        //判断$instance是否是Singleton的对象，不是则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self($appid,$appsecret);
        }
        return self::$instance;
    }

    /**
     * @desc 设置自定义菜单
     * @param array $data
     * @return bool
     */
    public function setMenu(array $data):bool
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->getGlobalAccessToken();
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $str = Http::curl('post',$url,$data);
        return $this->checkError($str);
    }

    /**
     * @desc 获取自定义菜单
     * @return string
     */
    public function getMenuInfo():string
    {
        $url = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=".$this->getGlobalAccessToken();
        $str = Http::curl('get',$url);
        if ($this->checkError($str)){
            return $str;
        }
        return '';
    }

    /**
     * @desc 删除自定义菜单
     * @return bool
     */
    public function delMenu():bool
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->getGlobalAccessToken();
        $str = Http::curl('get',$url);
        return $this->checkError($str);
    }

    /**
     * @desc 设置个性化菜单
     * @param array $data
     * @param array $matchrule
     * @return bool
     */
    public function setMenuConditional(array $data,array $matchrule):bool
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$this->getGlobalAccessToken();
        $arr = array();
        $arr = array_merge($data,$matchrule);
        $str = Http::curl('post',$url,json_encode($arr));
        return $this->checkError($str);
    }

    /**
     * @desc 获取个性化菜单
     * @return string
     */
    public function getMenuConditionalInfo():string
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->getGlobalAccessToken();
        $str = Http::curl('get',$url);
        return $this->checkError($str);
    }
}